package com.zhugang.week12;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @program algorithms
 * @description: threeSum2
 * @author: chanzhugang
 * @create: 2022/09/06 22:58
 */
public class ThreeSum2 {

    /**
     * 15 三数之和
     * 转成两数之和问题（思路一样）
     *
     * @param nums
     * @return
     */
    public List<List<Integer>> threeSum2(int[] nums) {
        // 双指针，和两数之和思路一样
        Arrays.sort(nums);
        List<List<Integer>> result = new ArrayList<>();
        int n = nums.length;

        for (int i = 0; i < n; i++) {
            if (i != 0 && nums[i - 1] == nums[i]) {
                // 避免a重复
                continue;
            }
            // 双指针处理后面两个数
            int p = i + 1;
            int q = n - 1;
            while (p < q) {
                if (p >= i + 2 && nums[p - 1] == nums[p]) {
                    p++;
                    // 避免b重复
                    continue;
                }
                if (q <= n - 2 && nums[q + 1] == nums[q]) {
                    q--;
                    // 避免c重复
                    continue;
                }
                int target = -(nums[p] + nums[q]);
                if (nums[i] == target) {
                    result.add(Arrays.asList(nums[i], nums[p], nums[q]));
                    p++;
                    q--;
                } else if (nums[i] < target) {
                    p++;
                } else {
                    q--;
                }
            }
        }
        return result;
    }
}